﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SPListTemplateManager {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();

            Helpers.GetAllWebApplications(false);

            if (Helpers.webAppsList.Count > 0) {
                Helpers.FillWebAppComboBox(comboBox1);
            } else {
                MessageBox.Show("No web application was found!");
            }
        }

        // web apps change --> get site colls
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
            comboBox2.Items.Clear();            
            listBox1.Items.Clear();
            //listBox2.Items.Clear();
            Cursor.Current = Cursors.WaitCursor;
            SPWebApplication selectedApp = (SPWebApplication)comboBox1.SelectedItem;

            foreach (SPWebApplication webApp in Helpers.webAppsList) {
                if (webApp == selectedApp) {
                    foreach (SPSite item in webApp.Sites) {
                        comboBox2.Items.Add(item.Url);
                    }
                    break;
                }
            }
        }

        private void btnGetTemplates_Click(object sender, EventArgs e) {
            listBox1.Items.Clear();
            listView1.Items.Clear();
            label3.Text = "";
            Cursor.Current = Cursors.WaitCursor;
            string selectedSiteColl = (string)comboBox2.SelectedItem;

            if (string.IsNullOrEmpty(selectedSiteColl)) {
                MessageBox.Show("You haven't selected site collection!");
            } else {
                using (SPSite site = new SPSite(selectedSiteColl)) {
                    using (SPWeb web = site.OpenWeb()) {
                        SPList templateList = web.Lists["List Template Gallery"];
                        SPListItemCollection itemColl = templateList.Items;

                        label3.Text = "Number of list templates: " + itemColl.Count;
                        listBox1.DisplayMember = "Title";

                        foreach (SPListItem item in itemColl) {
                            listBox1.Items.Add(item);
                        }
                    }
                }
            }

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) {
            listBox1.Items.Clear();
            listView1.Items.Clear();
            label3.Text = "";
        }

        SPListItem selectedTemplate = null;

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
            listView1.Items.Clear();
            Cursor.Current = Cursors.WaitCursor;
            selectedTemplate = (SPListItem)listBox1.SelectedItem;
            Cursor.Current = Cursors.WaitCursor;

            if (selectedTemplate != null) {
                listView1.Items.Add(new ListViewItem(new[] { "Name: ", selectedTemplate.Name }));
                listView1.Items.Add(new ListViewItem(new[] { "Language: ", Helpers.GetSPFieldStringValue(selectedTemplate, "Language", "") }));
                listView1.Items.Add(new ListViewItem(new[] { "Product Version: ", Helpers.GetSPFieldStringValue(selectedTemplate, "Product Version", "") }));
                listView1.Items.Add(new ListViewItem(new[] { "Created: ", Helpers.GetSPFieldStringValue(selectedTemplate, "Created", "") }));
                listView1.Items.Add(new ListViewItem(new[] { "Modified: ", Helpers.GetSPFieldStringValue(selectedTemplate, "Modified", "") }));
                listView1.Items.Add(new ListViewItem(new[] { "Feature ID: ", Helpers.GetSPFieldStringValue(selectedTemplate, "Feature ID", "") }));
                listView1.Items.Add(new ListViewItem(new[] { "Url: ", selectedTemplate.Url }));
            } else {
                MessageBox.Show("You haven't selected any template!");
            }
        }
        

        private void btnDeleteTemplate_Click(object sender, EventArgs e) {
            Cursor.Current = Cursors.WaitCursor;
            var confirmResult = MessageBox.Show("Are you sure to delete template from library ?", "Confirm Delete", MessageBoxButtons.YesNo);
            if (confirmResult == DialogResult.Yes) {                
                selectedTemplate = (SPListItem)listBox1.SelectedItem;
                if (selectedTemplate != null) {
                    int tempId = Helpers.GetSPFieldIntValue(selectedTemplate, "ID", 0);

                    string selectedSiteColl = (string)comboBox2.SelectedItem;

                    using (SPSite site = new SPSite(selectedSiteColl)) {
                        using (SPWeb web = site.OpenWeb()) {
                            SPList templateList = web.Lists["List Template Gallery"];

                            SPListItem item = templateList.GetItemById(tempId);

                            item.Delete();
                            MessageBox.Show("Template was deleted!");
                            btnGetTemplates.PerformClick();
                        }
                    }
                } else {
                    MessageBox.Show("You haven't selected any template!");
                }
            }
        }


        private void btnUploadTemplate_Click(object sender, EventArgs e) {

            string selectedSiteColl = (string)comboBox2.SelectedItem;

            if (!string.IsNullOrEmpty(selectedSiteColl)) {
                Stream myStream = null;

                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter = "list templates (*.stp)|*.stp";
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK) {
                    Cursor.Current = Cursors.WaitCursor;
                    try {
                        if ((myStream = openFileDialog1.OpenFile()) != null) {
                            using (myStream) {
                                //textBox1.Text = openFileDialog1.FileName;
                                using (SPSite site = new SPSite(selectedSiteColl)) {
                                    using (SPWeb web = site.OpenWeb()) {
                                        SPList templateList = web.Lists["List Template Gallery"];
                                        SPFolder root = templateList.RootFolder;
                                        SPFile spfile = root.Files.Add(root.Url + "/" +openFileDialog1.SafeFileName, myStream, true);
                                        btnGetTemplates.PerformClick();
                                        root.Update();
                                        MessageBox.Show("New template is added to library!");
                                    }
                                }
                            }
                        }
                    } catch (Exception ex) {
                        MessageBox.Show("ERROR: " + ex.Message);
                    }
                }
            } else {
                MessageBox.Show("You must select site collection!");
            }
        }

        private void btnSaveToDisk_Click(object sender, EventArgs e) {
            string selectedSiteColl = (string)comboBox2.SelectedItem;

            if (!string.IsNullOrEmpty(selectedSiteColl)) {
                selectedTemplate = (SPListItem)listBox1.SelectedItem;
                if (selectedTemplate != null) {

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    DialogResult result = fbd.ShowDialog();
                    if (result == DialogResult.OK) {
                        Cursor.Current = Cursors.WaitCursor;
                        try {
                            using (SPSite site = new SPSite(selectedSiteColl)) {
                                using (SPWeb web = site.OpenWeb()) {
                                    SPList templateList = web.Lists["List Template Gallery"];
                                    int tempId = Helpers.GetSPFieldIntValue(selectedTemplate, "ID", 0);

                                    SPFile file = templateList.GetItemById(tempId).File;
                                    if (file != null) {
                                        string filePath = Path.Combine(fbd.SelectedPath, file.Name);

                                        using (FileStream filestream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)) {
                                            byte[] bArray = file.OpenBinary();
                                            filestream.Write(bArray, 0, bArray.Length);
                                        }
                                    }
                                    MessageBox.Show("Template is downloaded to local folder!");
                                }
                            }
                        } catch (Exception ex) {
                            MessageBox.Show("ERROR: " + ex.Message);
                        }
                    }
                } else {
                    MessageBox.Show("You must select list template!");
                }
            } else {
                MessageBox.Show("You must select site collection!");
            }
        }

        private void btnSaveAsTemplate_Click(object sender, EventArgs e) {
            Form2 newTemplateForm = new Form2();
            newTemplateForm.Show();            
        }
    }
}
